package com.hx.juc.producerconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created  on 2019/05/03.
 */

/**
 * 实现只能生产一个，消费一个的关系，不能多生产，也不能多消费
 */
public class ProducerConsumerTradition {
    public static void main(String[] args) throws Exception {
        ShareData data = new ShareData();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    data.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "AA").start();

        }

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    data.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "BB").start();

        }


    }
}


/**
 * 资源类
 */
class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws Exception {
        lock.lock();
        try {
            while (number != 0) {
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws Exception {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
